import { ipcMain } from "electron";
import { Result } from "./result";

function success(r) {
  return JSON.stringify(Result.ok(r));
}

function failure(reason) {
  return JSON.stringify(Result.error(-1, reason));
}

let modules = {};

let ipcMappers = {};

let files = require.context("./modules", false, /\.js$/);

files.keys().forEach((key) => {
  modules[key.replace(/\.\/|\.js/g, "")] = files(key).default;
});

Object.keys(modules).forEach((key) => {
  Object.keys(modules[key]).forEach((mkey) => {
    let ikey = key + "." + mkey;

    ipcMappers[ikey] = modules[key][mkey];

    ipcMain.handle(ikey, async (event, json) => {
      let params = JSON.parse(json);
      try {
        var r = await ipcMappers[ikey](params);
        return success(r);
      } catch (err) {
        return failure(err.message);
      }
    });
  });
});

//console.log(modules);

console.log(ipcMappers);

// function test(params) {
//   console.log("test" + params);
//   return "test success！！！";
// }

// ipcMain.handle("test", async (event, json) => {
//   let params = JSON.parse(json);
//   try {
//     var r = test(params);
//     return success(r);
//   } catch (err) {
//     return failure(err.message);
//   }
// });
